package com.avcdata.aoscustommade.activity;

import android.content.Intent;
import android.text.SpannableString;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.avcdata.aoscustommade.R;
import com.avcdata.aoscustommade.bean.GetVerificationCodeBean;
import com.avcdata.aoscustommade.bean.VerifyNoteBean;
import com.avcdata.aoscustommade.main.BaseActivity;
import com.avcdata.aoscustommade.model.ForgetFindOrChangePasswordModel;
import com.avcdata.aoscustommade.model.LoginActivityModel;
import com.avcdata.aoscustommade.presenter.ForgetFindOrChangePasswordPresenter;
import com.avcdata.aoscustommade.utils.AppActivityManager;
import com.avcdata.aoscustommade.utils.AvcConstants;
import com.avcdata.aoscustommade.utils.SharedPreferencesUtils;
import com.avcdata.aoscustommade.utils.TextUitl;
import com.avcdata.aoscustommade.utils.ToastUtils;
import com.avcdata.aoscustommade.view.ForgetFindOrChangePasswordView;
import com.avcdata.aoscustommade.view.TimeCount;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import org.json.JSONException;
import org.json.JSONObject;


/**
 * 找回密码、修改密码页面
 */
public class ForgetFindOrChangePassword_Activity extends BaseActivity implements ForgetFindOrChangePasswordView {

    @ViewInject(R.id.leftImage)
    private ImageView leftImage;
    @ViewInject(R.id.leftText)
    private TextView leftText;
    @ViewInject(R.id.title)
    private TextView title;
    @ViewInject(R.id.findpassword_type)
    private TextView findpassword_type;
    @ViewInject(R.id.findpassword_account)
    private EditText findpassword_account;
    @ViewInject(R.id.findpassword_new)
    private EditText findpassword_new;
    @ViewInject(R.id.findpassword_again)
    private EditText findpassword_again;
    @ViewInject(R.id.findpassword_code)
    private EditText findpassword_code;
    @ViewInject(R.id.findpassword_codebtn)
    private Button findpassword_codebtn;
    @ViewInject(R.id.confrim)
    private Button confrim;


    private String type = "";
    private TimeCount timeCount;
    private SharedPreferencesUtils sp;
    private boolean isLogin = false;
    private ForgetFindOrChangePasswordPresenter forgetFindOrChangePasswordPresenter;

    @Override
    public void initView() {
        setContentView(R.layout.activity_forgetfindpassword);
        AppActivityManager.getAppManager().addActivity(this);
        ViewUtils.inject(this);
    }

    @Override
    public void initInstall() {
        sp = new SharedPreferencesUtils(this);
        type = getIntent().getStringExtra(AvcConstants.PASSWORDCHANGE);
        isLogin = getIntent().getBooleanExtra("isLogin", false);
        timeCount = new TimeCount(this, findpassword_code, findpassword_codebtn, 60000, 1000);
        if (isLogin) {
            if (type.equals("phone")) {
                title.setText(getResources().getString(R.string.login_forgotpassword2));
                findpassword_type.setText(getResources().getString(R.string.phone));
                SpannableString ss = new SpannableString(getResources().getString(R.string.find_bindphone));
                findpassword_account.setHint(ss); // 一定要进行转换,否则属性会消失
            } else if (type.equals("email")) {
                title.setText(getResources().getString(R.string.login_forgotpassword2));
                findpassword_type.setText(getResources().getString(R.string.email));
                SpannableString ss = new SpannableString(getResources().getString(R.string.find_bindemail));
                findpassword_account.setHint(ss); // 一定要进行转换,否则属性会消失
            }

        } else {
            if (TextUitl.isPhone(sp.getUserAccount())) {
                title.setText(getResources().getString(R.string.change_password));
                findpassword_type.setText(getResources().getString(R.string.account));
//                ss = new SpannableString(getResources().getString(R.string.find_bindphone));
                findpassword_account.setText(sp.getUserAccount());
//                findpassword_account.setText(TextUitl.phoneHide(sp.getUserAccount()));
            } else {
                title.setText(getResources().getString(R.string.change_password));
                findpassword_type.setText(getResources().getString(R.string.account));
//                ss = new SpannableString(getResources().getString(R.string.find_bindphone));
                findpassword_account.setText(sp.getUserAccount());
            }

        }

        if (!isLogin) {
            findpassword_account.setFocusable(false);
            findpassword_account.setFocusableInTouchMode(false);
            findpassword_account.setEnabled(false);
        }

        forgetFindOrChangePasswordPresenter = new ForgetFindOrChangePasswordPresenter(this, new ForgetFindOrChangePasswordModel(ForgetFindOrChangePassword_Activity.this), new LoginActivityModel(ForgetFindOrChangePassword_Activity.this));
    }

    @Override
    public void initData() {

    }

    @Override
    public void evenControl() {
        leftImage.setOnClickListener(this);
        leftText.setOnClickListener(this);
        findpassword_codebtn.setOnClickListener(this);
        confrim.setOnClickListener(this);
    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.leftImage:
            case R.id.leftText:
                AppActivityManager.getAppManager().finishActivity(this);
                break;
            case R.id.findpassword_codebtn:
                if (checkAccount()) {
                    if (findpassword_codebtn.getText().toString().trim().equals("重新获取")) {
                        findpassword_code.setText("");
                    }
                    loadCode();
                }
                break;
            case R.id.confrim:
                if (checkAccount() && checkPassword() && checkCode()) {
                    if (isLogin) {
                        loadCheackAccount();
                    } else {
                        loadCheckCode();
                    }
                }
                break;
        }
    }


    /**
     * 检验手机号是否存在
     */
    private void loadCheackAccount() {
        String account = TextUitl.getString(findpassword_account);
        boolean isPhone = TextUitl.isPhone(account);
        forgetFindOrChangePasswordPresenter.loadCheackAccount(isPhone, account);
    }

    // 验证手机号是否存在成功
    @Override
    public void loadCheackAccount(JSONObject jsonObject) {
        try {
            if (!TextUitl.isEmpty(jsonObject.toString())) {
                boolean returnValue = jsonObject.getBoolean("returnValue");
                if (returnValue) {
                    loadCheckCode();
                } else {
                    ToastUtils.showShort(ForgetFindOrChangePassword_Activity.this, "该账号不存在");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取验证码
     */
    private void loadCode() {
        timeCount.start();
        forgetFindOrChangePasswordPresenter.loadCode(TextUitl.getString(findpassword_account));
    }

    //获取手机验证码成功
    @Override
    public void loadCodeSuccess(GetVerificationCodeBean bean) {
        boolean success = bean.isSuccess();
        if (success) {
            ToastUtils.showShort(ForgetFindOrChangePassword_Activity.this, "验证码已发送");
        }
    }

    //获取手机验证码失败
    @Override
    public void loadCodeFailure() {

    }


    /**
     * 验证验证码
     */
    private void loadCheckCode() {
        forgetFindOrChangePasswordPresenter.loadCheckCode(TextUitl.getString(findpassword_account), TextUitl.getString(findpassword_code));
    }

    //验证验证码成功
    @Override
    public void loadCheckCodeSuccess(VerifyNoteBean bean) {
        if (bean != null){
            boolean success = bean.isSuccess();
            VerifyNoteBean.ReturnValueBean returnValue = bean.getReturnValue();
            if (success && returnValue != null) {
                String result = returnValue.getResult()+"";
                if (!TextUitl.isEmpty(result) && result.equals("3")) {
                    loadedType(0);
                }
            }
        }
    }


    /**
     * 账号重置
     */
    private void loadReset() {
        boolean isPhone = TextUitl.isPhone(sp.getUserAccount());
        String name = TextUitl.getString(findpassword_account);
        String password = TextUitl.getString(findpassword_again);
        forgetFindOrChangePasswordPresenter.loadReset(isPhone, name, password);
    }

    @Override
    public void loadResetSuccess(JSONObject jsonObject) {
        try {
            if (!TextUitl.isEmpty(jsonObject.toString())) {
                boolean success = jsonObject.getBoolean("success");
                if (success) {
                    sp.setUserPassword("");
                    loadedType(1);
                } else {
                    loadedType(-1);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }



    /**
     * 结果处理
     */
    private void loadedType(int num) {
        if (num == 0) {
            loadReset();
        } else {
            ToastUtils.showShort(ForgetFindOrChangePassword_Activity.this, "密码修改成功");
            Intent intent = new Intent(ForgetFindOrChangePassword_Activity.this, Login_Activity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    }


    /**
     * 验证手机
     *
     * @return
     */
    private boolean checkAccount() {
        if (TextUitl.isEmpty(TextUitl.getString(findpassword_account))) {
            ToastUtils.showShortSnackBar(this, this.getResources().getString(R.string.login_inputaccount));
            return false;
        } else {
            if (TextUitl.isPhone(TextUitl.getString(findpassword_account)) || TextUitl.isEmail(TextUitl.getString(findpassword_account))) {
                return true;
            } else {
                ToastUtils.showShortSnackBar(this, "请输入正确的手机号或邮箱");
                return false;
            }

        }

    }

    /**
     * 验证密码
     *
     * @return
     */
    private boolean checkPassword() {
        if (TextUitl.isEmpty(TextUitl.getString(findpassword_new))) {
            ToastUtils.showShortSnackBar(this, "请输入新密码");
            return false;
        }
        if (TextUitl.isEmpty(TextUitl.getString(findpassword_again))) {
            ToastUtils.showShortSnackBar(this, "请再次输入新密码");
            return false;
        }
        if (!TextUitl.getString(findpassword_new).equals(TextUitl.getString(findpassword_again))) {
            ToastUtils.showShortSnackBar(this, "请输入相同的密码");
            return false;
        }
        if (TextUitl.getString(findpassword_new).length() < 6 || TextUitl.getString(findpassword_again).length() < 6
                || TextUitl.getString(findpassword_new).length() > 20 || TextUitl.getString(findpassword_again).length() > 20) {
            ToastUtils.showShortSnackBar(this, "请输入6~20位的密码");
            return false;
        }
        return true;
    }


    /**
     * 验证验证码
     *
     * @return
     */
    private boolean checkCode() {
        if (TextUitl.isEmpty(TextUitl.getString(findpassword_code))) {
            ToastUtils.showShortSnackBar(this, this.getResources().getString(R.string.login_inputcode));
            return false;
        } else {
//            if (TextUitl.getString(findpassword_code).length() < 6) {
//                T.showShortSnackBar(this, "验证码最少6位");
//                return false;
//            }
        }

        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timeCount.cancel();
    }


}
